#!/usr/bin/python

import shutil
import pygtk
pygtk.require('2.0')
import gtk
import os,re
import socket, fcntl, struct

DEF_SVR_IP = ""
DEF_LOCAL_IP = ""
DEF_FLASH_MODE = "NAND_ECC_HW"
DEF_NFS_ROOT = ""
DEF_IMAGE_DIR = os.getenv("HOME") + "/maxwit/images"
CONFIG_MAC_ADDR = ""
DISPLAY_MAC_ADDR = ""

class MainWin:
	config = {}

	def delete_event(self, widget, event, data=None):
		print "delete event occurred"
		return False

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def change_plat(self, widget):
		if widget.get_active() == 0:
			self.config["ARCH"] = "arm"
			self.config["ARCH_VER"] = "armv4t"
			self.config["SOC_VENDOR"] = "samsung"
			self.config["CONSOLE"] = "ttySAC0"
			self.config["SOC_HEADER"] = "s3c24xx.h"
		elif widget.get_active() == 1:
			self.config["ARCH"] = "arm"
			self.config["ARCH_VER"] = "armv4t"
			self.config["SOC_VENDOR"] = "samsung"
			self.config["CONSOLE"] = "ttySAC0"
			self.config["SOC_HEADER"] = "s3c24xx.h"
		elif widget.get_active() == 2:
			self.config["ARCH"] = "arm"
			self.config["ARCH_VER"] = "armv5te"
			self.config["SOC_VENDOR"] = "atmel"
			self.config["CONSOLE"] = "ttyS0"
			self.config["SOC_HEADER"] = "at91sam926x.h"
		else:
			self.config["ARCH"] = "arm"
			self.config["ARCH_VER"] = "armv5te"
			self.config["SOC_VENDOR"] = "atmel"
			self.config["CONSOLE"] = "ttyS0"
			self.config["SOC_HEADER"] = "at91sam926x.h"
		self.entToolchain.set_text(self.config["ARCH"] + "-maxwit-linux-gnueabi-")
		
	def get_ip_address(self, ifname):
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		
		try:
			localIP=fcntl.ioctl(
				s.fileno(),
				0x8915,  # SIOCGIFADDR
				struct.pack('256s', ifname[:15])
				)
		except IOError:
			return "0.0.0.0"
		return socket.inet_ntoa(localIP[20:24])


	def ecc_option(self, widget, data=None):
		global DEF_FLASH_MODE 
		if widget.get_active() == True:
			DEF_FLASH_MODE = data

	def mac_display2build(self, display):
			mac = display.split(':')	
			return "{0x%s,0x%s,0x%s,0x%s,0x%s,0x%s}" % \
			(mac[0],mac[1],mac[2],mac[3],mac[4],mac[5])

	def default_server_ip(self):
		global DEF_SVR_IP
   		DEF_SVR_IP = self.get_ip_address('eth0')		
	
		return DEF_SVR_IP

	def default_local_ip(self):
		global DEF_LOCAL_IP
		DEF_LOCAL_IP = "1" + os.popen("date +%S").read().replace('\n', '') 
		DEF_LOCAL_IP = self.default_server_ip().rsplit(".", 1)[0] +\
			"." + DEF_LOCAL_IP
		return DEF_LOCAL_IP

	def ip_display2build(self, display):
			ip = display.split('.')	
			return "%s,%s,%s,%s" % \
			(ip[0],ip[1],ip[2],ip[3])

	def default_mac_address(self):
		global DISPLAY_MAC_ADDR
		BUILD_YEAR = os.popen("date +%y").read().replace("\n", "") 
		BUILD_MONTH = os.popen("date +%m").read().replace("\n", "") 
		BUILD_DAY = os.popen("date +%d").read().replace("\n", "") 
		HOUR = os.popen("date +%H").read().replace("\n", "") 
		MIN = os.popen("date +%M").read().replace("\n", "") 
		DISPLAY_MAC_ADDR = "10:%s:%s:%s:%s:%s" % (BUILD_YEAR, BUILD_MONTH, BUILD_DAY, HOUR, MIN)

		return DISPLAY_MAC_ADDR

	def default_nfs_root(self):
		global DEF_NFS_ROOT
		DEF_NFS_ROOT = os.getenv("HOME") + "/maxwit/rootfs"
		return DEF_NFS_ROOT	
	
	def save_config(self,button):
		DEF_SVR_IP = self.ip_display2build(self.entServer.get_text())
		DEF_LOCAL_IP = self.ip_display2build(self.entLocal.get_text())
		DEF_NFS_ROOT = self.entNFS.get_text()	
		s1 =  self.entMAC.get_text()
		CONFIG_MAC_ADDR = self.mac_display2build(s1)
		
		soc = self.cmbPlat.get_active_text()
		fnDefConfig = 'arch/' + self.config["ARCH"] + '/' + self.config["SOC_VENDOR"] + '/' + soc.lower() + '-config.mk'
		fnCurConfig = 'Makefile'
		shutil.copyfile(fnDefConfig, fnCurConfig)
		fCurConfig = open(fnCurConfig, 'a')
		fCurConfig.write('\n')
		fCurConfig.write("ARCH = " + self.config["ARCH"] + '\n')
		fCurConfig.write("ARCH_VER = " + self.config["ARCH_VER"] + '\n')
		fCurConfig.write("SOC = " + soc + '\n')	
		fCurConfig.write("SOC_VENDOR = " + self.config["SOC_VENDOR"] + '\n')
		fCurConfig.write("CROSS_COMPILE = " + self.entToolchain.get_text() + '\n\n')
		fCurConfig.write("IMAGE_OUT_DIR= %s"  %DEF_IMAGE_DIR + '\n\n')

		fMakein = open('Makefile.in', 'r')
		for eachline in fMakein:
			fCurConfig.write(eachline)
		fMakein.close()
		fCurConfig.close()

		fAutoConf = open('include/autoconf.h', 'w')
		fAutoConf.write('#pragma once\n\n')
		fAutoConf.write('// general\n')
		fAutoConf.write('#define CONF_' + soc + '\n')
		fAutoConf.write('#define CONF_PLAT_NAME \"' + soc + '\"\n')
		fAutoConf.write('// uart\n')
		fAutoConf.write('#define CONF_UART_INDEX  0\n')
		fAutoConf.write('// flash\n')
		fAutoConf.write("#define CONF_NAND_ECC_MODE %s\n" % DEF_FLASH_MODE)
		fAutoConf.write('// network\n')
		fAutoConf.write('#define CONF_NET_MASK MKIP(255,255,255,0)\n')
		fAutoConf.write('#define CONF_LOCAL_IP MKIP(%s)\n'%	DEF_LOCAL_IP)
		fAutoConf.write("#define CONF_SVR_IP MKIP(%s)\n"% DEF_SVR_IP)
		fAutoConf.write('#define CONF_MAC_ADDR %s\n' % CONFIG_MAC_ADDR)
		fAutoConf.write('// boot\n')
		fAutoConf.write("#define CONF_NFS_ROOT \"%s\"\n" %DEF_NFS_ROOT)
		fAutoConf.write('#define CONF_CONSOLE_NAME \"' + self.config["CONSOLE"] + '\"\n')
		fAutoConf.write('\n')
		fAutoConf.write('#include <arch/' + self.config['SOC_HEADER'] + '>\n')
		fAutoConf.close()

		gtk.main_quit()

	def __init__(self):
		self.config["CONSOLE"] = "ttyS0"

		self.window = gtk.Window()
		self.window.set_border_width(10)
		self.window.set_title("MaxWit g-bios (V1.0)")
		self.window.move(300, 100)
		self.window.resize(330, 200)
		self.window.connect("destroy", self.destroy)

		vbox = gtk.VBox(False, 2)
		self.window.add(vbox)

		labPlat = gtk.Label("Platform:")
		self.cmbPlat = gtk.combo_box_new_text()
		labToolchain = gtk.Label("Toolchain:")
		self.entToolchain = gtk.Entry()
		self.entToolchain.set_size_request(210,30)
		self.cmbPlat.connect("changed", self.change_plat)
		self.cmbPlat.append_text("S3C2410")
		self.cmbPlat.append_text("S3C2440")
		self.cmbPlat.append_text("AT91SAM9261")
		self.cmbPlat.append_text("AT91SAM9263")
		self.cmbPlat.set_active(1)
			
		# network interface		
		# sever ip
		labServer = gtk.Label("Server IP:")
		self.entServer = gtk.Entry()
		self.entServer.set_size_request(140,30)
		self.entServer.set_text(self.default_server_ip())
		# local ip
		labLocal = gtk.Label("Local IP:")
		self.entLocal = gtk.Entry()
		self.entLocal.set_size_request(140,30)
		self.entLocal.set_text(self.default_local_ip())
		# MAC address
		labMAC = gtk.Label("MAC:")
		self.entMAC = gtk.Entry()
		self.entMAC.set_size_request(140,30)
		self.entMAC.set_text(self.default_mac_address())
		# default NFS path
		labNFS = gtk.Label("NFS Path:")
		self.entNFS = gtk.Entry()
		self.entNFS.set_size_request(140,30)
		self.entNFS.set_text(self.default_nfs_root())
		
		# flash interface 
		RadioButton1 = gtk.RadioButton(None, "Hardware")
		RadioButton1.connect("toggled", self.ecc_option, "NAND_ECC_HW")

		RadioButton2 = gtk.RadioButton(RadioButton1, "Software")
		RadioButton2.connect("toggled", self.ecc_option, "NAND_ECC_SW")
		RadioButton2.set_active(False)

		RadioButton3 = gtk.RadioButton(RadioButton1, "None")
		RadioButton3.connect("toggled", self.ecc_option, "NAND_ECC_NONE")

		btnBuild = gtk.Button("Build")
		btnBuild.set_size_request(100,30)
		btnBuild.connect("clicked",self.save_config)

		table1 = gtk.Table(2, 2, False)
		table1.attach(labPlat, 0, 1, 0, 1, 0, 0, 5, 5)
		table1.attach(self.cmbPlat, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		table1.attach(labToolchain, 0, 1, 1, 2, 0, 0, 5, 5)
		table1.attach(self.entToolchain, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)

		table2 = gtk.Table(4, 2, False)
		table2.attach(labServer, 0, 1, 0, 1, 0, 0, 5, 5)
		table2.attach(self.entServer, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		table2.attach(labLocal, 0, 1, 1, 2, 0, 0, 5, 5)
		table2.attach(self.entLocal, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		table2.attach(labMAC, 0, 1, 2, 3, 0, 0, 5, 5)
		table2.attach(self.entMAC, 1, 2, 2, 3, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		table2.attach(labNFS, 0, 1, 3, 4, 0, 0, 5, 5)
		table2.attach(self.entNFS, 1, 2, 3, 4, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		
		table3 = gtk.Table(1, 3, True)
		table3.attach(RadioButton1, 0, 1, 0, 1, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		table3.attach(RadioButton2, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)
		table3.attach(RadioButton3, 2, 3, 0, 1, gtk.EXPAND|gtk.FILL, gtk.EXPAND|gtk.FILL, 5, 5)

		box4 = gtk.HBox(False, 0)
		box4.pack_start(btnBuild, True, False, 0)

		frame = gtk.Frame("General")
		frame.add(table1)
		vbox.pack_start(frame, False, False, 0)
		frame = gtk.Frame("Network")
		frame.add(table2)
		vbox.pack_start(frame, False, False, 0)
		frame = gtk.Frame("Flash ECC Mode")
		frame.add(table3)
		vbox.pack_start(frame, False, False, 0)
		vbox.pack_start(box4, False, False, 0)
		
		self.window.show_all()
		
	def main(self):
		gtk.main()

if __name__ == "__main__":
	MainWin().main()

